package com.kinghunt.misp.web.advice;

import com.kinghunt.misp.web.context.ApiContext;
import com.bygoodtech.kings.common.dto.ApiResult;
import com.bygoodtech.kings.common.exception.ServiceResponseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

/**
 * 异常包装切面
 */
@RestControllerAdvice
@Slf4j
public class ExceptionAspect {

    /**
     * 业务异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(ServiceResponseException.class)
    public ApiResult<Void> handleServiceResponseException(Exception e, HttpServletRequest request) {
        recordLog(request, e);
        String errorMsg = StringUtils.isBlank(e.getMessage()) ? "系统异常，请稍后重试" : e.getMessage();
        return ApiResult.fail(String.valueOf(-1), errorMsg);
    }


    /**
     * 未知异常
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public ApiResult<Void> handleException(Exception e, HttpServletRequest request) {
        recordLog(request, e);
        String errorMsg = StringUtils.isBlank(e.getMessage()) ? "系统异常，请稍后重试" : e.getMessage();
        return ApiResult.fail(String.valueOf(-1), errorMsg);
    }

    private void recordLog(HttpServletRequest request, Exception e) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        StringBuilder builder = new StringBuilder();
        if (!CollectionUtils.isEmpty(parameterMap)) {
            parameterMap.forEach((k, v) -> builder.append(k).append("=").append(Arrays.toString(v)).append(","));
        }

        log.error("user: {}, uri: {}, header:{}, parameter: {}, error: {}",
                ApiContext.apiUser(), request.getRequestURI(), ApiContext.requestHeader(), builder, e.getMessage(), e);
    }
}
